package cn.mastercom.bigdata.util.hadoop.hdfs;

import java.util.Date;
import java.util.List;

public class DirDownloadAndUploadTask extends DownloadAndUploadTask {
	
	private List<DownloadAndUploadTask> subTasks;
	
	private int countCompletedTasks = 0;
	private int countErrorTasks = 0;
	private int countSuspendedTasks = 0;
	
	public DirDownloadAndUploadTask(
			List<DownloadAndUploadTask> subTasks,
			String fileName,
			TaskType taskType) 
	{
		this.subTasks = subTasks;
		this.fileName = fileName;
		this.taskType = taskType;
		this.startDate = new Date();
		this.progress = -1;
	}

	@Override
	public int getProgress() {
		if (progress==100) return 100;
		
		int cnt = 0;
		for (DownloadAndUploadTask task : subTasks) {
			if (task.isComplete()) {
				cnt++;
			}
		}
		if (cnt == subTasks.size() && endDate != null) {
			endDate = new Date();
		}
		progress = (int)((cnt/(double)subTasks.size())*100);
		return (int) progress;
	}
	
	@Override
	public Date getEndDate() {
		if (endDate!=null) return endDate;
		if (this.isComplete) {
			endDate = new Date();
		}
		return endDate;
	}
	
	@Override
	public void suspend() {
		if (isComplete) return;
		for (DownloadAndUploadTask task : subTasks) {
			if (task.isComplete) continue;
			task.isSuspend = true;
		}
		this.isSuspend = true;
	}

	@Override
	public void start() {
		if (isComplete) return;
		for (DownloadAndUploadTask task : subTasks) {
			if (task.isComplete) continue;
			task.isStart = true;
		}
		this.isStart = true;
	}

	@Override
	public void pause() {
		if (isComplete) return;
		for (DownloadAndUploadTask task : subTasks) {
			if (task.isComplete) continue;
			task.isStart = false;
		}
		this.isStart = false;
	}
	
	@Override
	public void getTaskInfo() {
		if (this.isComplete || this.isSuspend) return;

		countCompletedTasks = 0;
		countErrorTasks = 0;
		countSuspendedTasks = 0;
		for (DownloadAndUploadTask task : subTasks) {
			if (task.isComplete) {
				countCompletedTasks++;
			}
			if (task.hasError) {
				countErrorTasks++;
			}
			if (task.isSuspend) {
				countSuspendedTasks++;
			}
		}
		
		if (endDate == null && 
				countCompletedTasks + countErrorTasks + countSuspendedTasks == subTasks.size()) {
			endDate = new Date();
		}
	}
	
	@Override
	public String getStatus() {
		return "完成任务(" + countCompletedTasks + "/" + subTasks.size() + ")，"
				+ "中止任务(" + countSuspendedTasks + "/" + subTasks.size() + ")，"
				+ "异常任务(" + countErrorTasks + "/" + subTasks.size() + ")";
	}
}
